package com.loong.framework.utils;

public class DistanceCalculatorUtil {
  // 地球半径，单位为千米
  private static final double EARTH_RADIUS = 6371.0;

  // 将角度转换为弧度
  private static double toRadians(double degrees) {
    return Math.toRadians(degrees);
  }

  // 计算两个经纬度之间的距离，单位为千米
  public static double calculateDistance(double lat1, double lon1, double lat2, double lon2) {
    // 将经纬度转换为弧度
    double radLat1 = toRadians(lat1);
    double radLon1 = toRadians(lon1);
    double radLat2 = toRadians(lat2);
    double radLon2 = toRadians(lon2);

    // 计算经纬度之间的差值
    double deltaLat = radLat2 - radLat1;
    double deltaLon = radLon2 - radLon1;

    // 使用 Haversine 公式计算两个地点之间的距离
    double a =
        Math.pow(Math.sin(deltaLat / 2), 2)
            + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(deltaLon / 2), 2);
    double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));

    // 返回距离，以千米为单位
    return EARTH_RADIUS * c;
  }
}
